/**
 * 
 */
package edu.umd.clip.lm.nbest;

import java.io.*;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.util.*;

import edu.umd.clip.lm.nbest.NbestFormat.NbestFormatData;
/**
 * @author Denis Filimonov <den@cs.umd.edu>
 *
 */
public class NbestFile {
	private NbestFormat format;
	private ArrayList<NbestFormatData> items;
	
	public NbestFile(NbestFormat format) {
		super();
		this.format = format;
		items = new ArrayList<NbestFormatData>();
	}

	public static NbestFile readFile(InputStream in) throws IOException, ParseException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")));

		NbestFormat format = null;

		String line = reader.readLine();
		if (line == null) return null;
		if (line.equalsIgnoreCase(NbestListOneFormat.HEADER)) {
			format = new NbestListOneFormat();
			line = reader.readLine();
		} else {
			format = new SRINbestFormat();
		}

		NbestFile nbest = new NbestFile(format);
		do {
			NbestFormatData item = format.parse(line);
			nbest.add(item);
			line = reader.readLine();
		} while(line != null);

		return nbest;
			
	}
	
	public void add(NbestFormatData item) {
		items.add(item);
	}
	
	public void writeFile(OutputStream out) throws IOException {
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, Charset.forName("UTF-8")));
		writer.append(format.makeHeader());
		for(NbestFormatData item : items) {
			writer.append(format.toString(item));
		}
		writer.flush();
	}

	public ArrayList<NbestFormatData> getItems() {
		return items;
	}

	public void setItems(ArrayList<NbestFormatData> items) {
		this.items = items;
	}

	public NbestFormat getFormat() {
		return format;
	}
	
}
